<?php

/**

 * 基类控制器
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Index\Controller;

use Think\Controller;
use Org\Util\Rbac;

class BaseController extends Controller {

    public $model;
    public $limit = 20;

    public function _initialize() {
        //9月22日系统升级
//        exit("<span style='font-size:4em;padding:1em;display:inline-block'>系统维护中...</span>");
        // session(null);

        /**
         * 微信id:userid
         * 微信头像:avatar
        */
        if (!session('openid')) {
            if ((isset($_GET['code']))) {
                $user = checkUser($_GET['code']);
                $openid = $user['openid'];  //获取用户openid
                session('openid', $openid);
                session('head', $user['avatar']);  //微信头像
                //获取用户表中的对应用户信息
                $map['openid'] = $openid;
                $userData = M('user')->where($map)->find();
                //增加该用户的userid
                if (!$userData) {
                    unset($map);
                    $map['USER_NAME'] = $user['name'];
                    $data['openid'] = $openid;
                    $data['head'] = $user['avatar'];
                    M('user')->where($map)->save($data);    //加openid
                    $userData = M('user')->where($map)->find();
                }
                //更新头像
                if ($userData['head'] != $user['avatar']) {
                    $hdata['head'] = $user['avatar'];
                    $hMap['openid'] = $openid;
                    M('user')->where($hMap)->save($hdata);
                }
                session('user_id', $userData['user_id']);
                session('byname', $userData['byname']);
                session('user_name', $userData['user_name']);
                session('dept_id', $userData['dept_id']);
                session('dept_id_other', $userData['dept_id_other']);
                session('user_priv', $userData['user_priv']);
                session('user_priv_other', $userData['user_priv_other']);
                $this->userInfo = $userData;
                //添加登录日志
                $logData['is_mobile'] = $userData['is_mobile'] + 1;
                $logData['mobile_login_time'] = time();
                $logData['LAST_VISIT_IP'] = the_public_ip();
                $logData['LAST_VISIT_TIME'] = date('Y-m-d H:i:s');
                M('user')->where($map)->save($logData);
                //统计当月登录次数
                $loginData['user_id'] = $userData['user_id'];
                $loginData['login_time'] = time();
                $loginData['type'] = 1; //移动端登录
                M('user_login')->add($loginData);
            } else {
                //用户授权登录
                $web = M('web')->where('id=' . I('webid'))->find();
                session('webid', I('webid'));
                session('pcId', I('id'));
                vendor('Mpwexin');
                $mp_weixin = new \Mpwexin();
                $url = $mp_weixin->getCode($web['wx_corpid'], $web['web_urls'] . '/index.php/Index/' . CONTROLLER_NAME . '/' . ACTION_NAME, 'snsapi_userinfo', $web['wx_agentid']);
                //header('location:' . $url);
                redirect($url);
            }
        } else {
            $map['USER_ID'] = session('user_id');
            $userData = M('user')->where($map)->find();
            $this->userInfo = $userData;
        }

//        if (!session('user_id')) {
//            $this->redirect('Index/Login/index');
//        } else {
//            $userData = M('user')->where('USER_ID="' . session('user_id') . '"')->find();
//            $this->userInfo = $userData;
//        }
        //如果user表中没有head，添加
        if (!$userData['head']) {
            $saveData['head'] = session('head');
            $saveData['openid'] = session('openid');
            $saveMap['USER_ID'] = session('user_id');
            M('user')->where($saveMap)->save($saveData);
        }

        //获取当前用户角色排序号
        $this->privNo = M('user_priv')->where('USER_PRIV=' . $userData['user_priv'])->getField('PRIV_NO');
        $this->user = session('user_id');

        //连接远程服务器
//        $host = '192.168.2.3';
//        $port = 83;
//        $conn = ftp_connect($host,$port);
//        var_dump($conn);
    }

    //备份数据库
    public function copyDatabase() {
        $zip = new \ZipArchive();
        $dir = './Public/Zip/';
        $filename = date('Ymd') . '.zip';

        //zip文件夹中只保留最新的一个临时文件
        if ($fh = opendir($dir)) {
            while (false !== ($file = readdir($fh))) {
                if ($file != "." && $file != "..") {
                    //echo $dir.$file,'<br/>';
                    if ($file != $filename) {
                        @unlink($dir . $file);
                        fopen($dir . $filename, 'w');
                        if ($zip->open($dir . $filename, \ZipArchive::OVERWRITE) === true) {
                            addFileToZip('e:/YOGOA/data5/OA/', $zip);
                            $zip->close();
                        }
                    }
                }
            }
            closedir($fh);
        }
    }

    /**
     *  获取微信接口权限数据
     */
    public function getAccessToken() {
        getToken();
        $ticket = getTicket();                  //微信签名ticket
        $timestamp = time();
        $web = M("web")->find(1);
        $data['wx_appid'] = $web['wx_appid'];   //微信APPID
        $data['nonceStr'] = "mpWeixin";         //签名随机字符串
        $data['timestamp'] = $timestamp;        //签名时间戳
        $signature = "jsapi_ticket=" . $ticket . "&noncestr=mpWeixin&timestamp=" . $timestamp . "&url=http://" . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"];
        $data["signature"] = sha1($signature);
        $this->data = $data;
//        $this->ajaxReturn($data);
    }

    //分页
    protected function pageLists($count, $limit = 9) {
        $Page = new \Think\Page($count, $limit);
        $Page->setConfig('prev', '<<');
        $Page->setConfig('next', '>>');
        //$Page->setConfig('first', '首页');
        //$Page->setConfig('last', '尾页');
        $Page->rollPage = 4;

        return $Page->show();
    }

    /*
     * 获取未办结和已办结列表
     * param    $flag   array   prcs_flag   0:全部
     * param    $type   int     1:未办结工作    2:已办结工作  0:全部
     * return array
     */

    protected function getLists1($flag, $limit, $type, $where = "") {
        $p = I('get.p', 1, 'intval');

        $start = $limit * ($p - 1);
        //$map['USER_ID'] = session('user_id');
        //$map['PRCS_FLAG'] = array('in', $flag);
        if ($flag) {
            $flag = rtrim(implode(',', $flag), ',');
            $sql = "select c.RUN_ID,c.PRCS_ID,c.FLOW_PRCS,c.USER_ID,c.PRCS_FLAG,c.CREATE_TIME,d.RUN_NAME,d.FLOW_ID,d.DEL_FLAG,d.BEGIN_USER from flow_run d ,(select a.* from flow_run_prcs a where PRCS_ID = (select max(PRCS_ID) from flow_run_prcs where RUN_ID = a.RUN_ID and USER_ID = '" . session('user_id') . "') order by a.RUN_ID) as c where d.RUN_ID = c.RUN_ID";
            $sql .= " and c.PRCS_FLAG in (" . $flag . ") and c.USER_ID = '" . session('user_id') . "' and d.DEL_FLAG = 0 order by d.RUN_id desc limit " . $start . "," . $limit;
        } else {
            $sql = "select c.RUN_ID,c.PRCS_ID,c.FLOW_PRCS,c.USER_ID,c.PRCS_FLAG,c.CREATE_TIME,d.RUN_NAME,d.FLOW_ID,d.DEL_FLAG,d.BEGIN_USER from flow_run d ,(select a.* from flow_run_prcs a where PRCS_ID = (select max(PRCS_ID) from flow_run_prcs where RUN_ID = a.RUN_ID and USER_ID = '" . session('user_id') . "') order by a.RUN_ID) as c where d.RUN_ID = c.RUN_ID";
            $sql .= " and c.USER_ID = '" . session('user_id') . "' and d.DEL_FLAG = 0 " . $where . " order by d.RUN_id desc limit " . $start . "," . $limit;
        }
        $runs = M()->query($sql);

        //$runs = M(flow_run_prcs)->field('run_id,prcs_id,flow_prcs,user_id,prcs_flag,create_time')->where($map)->page($start, $this->limit)->order('run_id desc')->select();
//        print_r($runs);die;
        foreach ($runs as $key => $row) {
            //获取表单id
            $tMap['FLOW_ID'] = $row['flow_id'];
            $runs[$key]['flow_type'] = M('flow_type')->field('flow_name,form_id,flow_sort')->where($tMap)->find();

            //获取文件名
            $dMap['RUN_ID'] = $row['run_id'];
            if ($row['flow_id'] == '98') {
                $dMap['ITEM_ID'] = 7;
            }
            if ($row['flow_id'] == '93') {
                $dMap['ITEM_ID'] = 20;
            }
            if ($row['flow_id'] == '106') {
                $dMap['ITEM_ID'] = 4;
            }
            if ($row['flow_id'] == '138') {
                $dMap['ITEM_ID'] = 39;
            }
            if ($dMap['ITEM_ID']) {
                $runs[$key]['title'] = M('flow_run_data')->where($dMap)->getField('item_data');
            }

            //获取进度名
            $pMap['FLOW_ID'] = $row['flow_id'];
            $pMap['PRCS_ID'] = $row['flow_prcs'];
            $runs[$key]['process'] = M('flow_process')->where($pMap)->getField('PRCS_NAME');

            //获取当前流程总进度
            $maxMap['FLOW_ID'] = $row['flow_id'];
            $runs[$key]['maxPrcs'] = M('flow_process')->where($maxMap)->max('prcs_id');

            //获取当前处理人 flow_run_prcs prcs_flag=3(已转交) or prcs_flag=4(已办结)
            $uMap['RUN_ID'] = $row['run_id'];
            if ($type == 1) {
                $uMap['PRCS_FLAG'] = array('in', [1, 2]);
                //$user = M('flow_run_prcs')->where($uMap)->getField('user_id');
            } elseif ($type == 2) {
                $uMap['PRCS_FLAG'] = array('in', [3, 4]);
//                $uMap['PRCS_FLAG'] = 4;
//                $user = M('flow_run_prcs')->where($uMap)->getField('user_id');
//                if (!$user) {
//                    $uMap['PRCS_ID'] = $row['prcs_id'] - 1; //上一步骤序号
//                    $uMap['PRCS_FLAG'] = 3;
//                    $user = M('flow_run_prcs')->where($uMap)->getField('user_id');
//                }
            }
            $user = M('flow_run_prcs')->where($uMap)->order('PRCS_ID DESC,PRCS_TIME DESC')->limit(1)->getField('user_id');
            $prcs = M('flow_run_prcs')->where($uMap)->order('PRCS_ID DESC,PRCS_TIME DESC')->limit(1)->getField('flow_prcs');
            $runs[$key]['user'] = $user;
            $runs[$key]['prcs'] = $prcs;

            //获取当前处理步骤
            $runs[$key]['prcs_name'] = getStepName($row['flow_id'], $prcs);
        }
        //print_r($runs);
        return $runs;
    }

    protected function getLists($flag, $limit, $type, $where = "") {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);

        if ($flag) {
            $flag = rtrim(implode(',', $flag), ',');
            $map['USER_ID'] = session('user_id');
            $map['PRCS_FLAG'] = array('in', $flag);
            //取所有和我相关的run_id
            $ids = M('flow_run_prcs')->where($map)->getField('run_id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
        } else {
            $map['USER_ID'] = session('user_id');
            //取所有和我相关的run_id
            $ids = M('flow_run_prcs')->where($map)->getField('run_id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
        }

        $rMap['RUN_ID'] = array('in', $ids);
        $rMap['DEL_FLAG'] = 0;
        $runs = M('flow_run')->field('RUN_ID,RUN_NAME,FLOW_ID,BEGIN_USER,DEL_FLAG')->where($rMap)->page($p, $start)->order('BEGIN_TIME desc')->select();

        foreach ($runs as $key => $row) {
            //获取表单信息（名称，from_id,排序）
            $tMap['RUN_ID'] = $row['run_id'];
            $flow_id = $row['flow_id'];
            $runs[$key]['flow_type'] = M('flow_type')->field('flow_name,form_id,flow_sort')->where('FLOW_ID=' . $flow_id)->find();

            //取创建时间
            $runs[$key]['create_time'] = M('flow_run_prcs')->where(array('RUN_ID' => $row['run_id'], 'USER_ID' => session('user_id')))->getField('CREATE_TIME');

            //获取当前流程总进度
            $maxMap['FLOW_ID'] = $flow_id;
            $runs[$key]['maxPrcs'] = M('flow_process')->where($maxMap)->max('prcs_id');

            //获取文件名
            $dMap['RUN_ID'] = $row['run_id'];
            if ($flow_id == '98') {
                $dMap['ITEM_ID'] = 7;
            }
            if ($flow_id == '93') {
                $dMap['ITEM_ID'] = 20;
            }
            if ($flow_id == '106') {
                $dMap['ITEM_ID'] = 4;
            }
            if ($flow_id == '138') {
                $dMap['ITEM_ID'] = 39;
            }
            if ($dMap['ITEM_ID']) {
                $runs[$key]['title'] = M('flow_run_data')->where($dMap)->getField('item_data');
            }

            //获取当前处理人 flow_run_prcs prcs_flag=3(已转交) or prcs_flag=4(已办结)
            $uMap['RUN_ID'] = $row['run_id'];
            if ($type == 1) {
                $uMap['PRCS_FLAG'] = array('in', [1, 2]);
            } elseif ($type == 2) {
                $uMap['PRCS_FLAG'] = array('in', [3, 4]);
            }
            $tmp = M('flow_run_prcs')->where($uMap)->order('PRCS_ID DESC,PRCS_TIME DESC')->limit(1)->find();
            $runs[$key]['user'] = $tmp['user_id'];
            $runs[$key]['prcs'] = $tmp['flow_prcs'];
            $runs[$key]['currPrcs'] = $tmp['prcs_id'];

            //获取当前处理步骤
            $runs[$key]['prcs_name'] = getStepName($flow_id, $runs[$key]['prcs']);
        }
        //print_r($runs);
        return $runs;
    }

    //文件上传
    protected function upfile($url) {
        $file = $_POST['imgfile'];
        $filename = end(explode('\\', $file));

        $config = array(
            'maxSize' => 20971520,
            'rootPath' => $url,
            'exts' => array('txt', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt','pptx', 'png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif', 'tiff', 'zip', 'html'),
            'savePath' => '', //保存路径
            'subName' => '',
        );
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传文件 

        $info = $upload->uploadOne($_FILES['imgfile']);
        $url = $filename . ';' . substr($url, 1) . $info['savepath'] . $info['savename'];
        if (!$info) {
            $this->ajaxReturn("false", "EVAL");
        } else {
            $this->ajaxReturn($url, "EVAL");
        }
    }

    public function delFile() {
        $url = I('url');
        if ($url) {
            $res = @unlink('.' . $url);
        }
        //$return['status'] = $res !== false ? true : false;
        $return['status'] = true;
        $this->ajaxReturn($return);
    }

    /*
     * 通过流程步骤设置的条件，取出对应的用户
     * param $flow_id   流程id
     * param $prcs_id   步骤id
     * param $run_id    发起流程id
     * param $auto_type 自动选人规则 0：不自动选择
     * param $dept_id   部门id
     * return array
     */

    protected function getData($flow_id = '', $prcs_id = '', $run_id = '', $auto_type = '', $dept_id = '', $limit = '') {
        $limit = $limit ? $limit : $this->limit;
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);
        if (!$auto_type && $dept_id) {
            $sql = "select USER_ID,USER_NAME,DEPT_ID,user.USER_PRIV,PRIV_NAME,PRIV_NO from user left join user_priv on user.USER_PRIV = user_priv.USER_PRIV where DEPT_ID = " . $dept_id . " order by PRIV_NO limit " . $start . "," . $limit;
            $data = M()->query($sql);

            //获取总条数
            $sql1 = "select count(*) from user left join user_priv on user.USER_PRIV = user_priv.USER_PRIV where DEPT_ID = " . $dept_id;
            $count = M()->query($sql1);
            foreach ($data as $key => $row) {
                $data[$key]['checked'] = 0;
                $data[$key]['count'] = $count[0]['count(*)'];
            }
        } else {
            if ($auto_type == 1) {
                $map['RUN_ID'] = $run_id;
                $map['PRCS_ID'] = 1;
                $sql['USER_ID'] = M('flow_run_prcs')->where($map)->getField('user_id');
            } else {
                if ($flow_id || $run_id) {
                    $map['FLOW_ID'] = $flow_id;
                    $map['PRCS_ID'] = $prcs_id;
                    $step = M('flow_process')->field('PRCS_ID,PRCS_NAME,PRCS_DEPT,PRCS_PRIV,PRCS_USER,PRCS_TO,FEEDBACK,PRCS_IN,PRCS_IN_SET,ALLOW_BACK,TOP_DEFAULT')->where($map)->find();

                    $sql = '';

                    //如果$dept_id存在，为指定部门（选人页面，点击部门时用）
                    if ($dept_id) {
                        $sql .= "DEPT_ID = " . $dept_id;
                    }

                    //$dept_id不存在，通过当前步骤获取部门（下一步页面获取符合条件的用户时用）
                    $is_str = strstr($step['prcs_name'], '部门');
                    if (($step['prcs_dept'] == '') && $is_str !== false) {
                        //如果当前步骤名包含部门并且步骤中部门为空，则获取第一步经办人的部门
                        unset($map['PRCS_ID']);
                        $map['RUN_ID'] = $run_id;
                        $uMap['USER_ID'] = M('flow_run')->where($map)->getField('BEGIN_USER');
                        $user = M('user')->field('USER_ID,USER_NAME,USER_PRIV,USER_PRIV_OTHER,DEPT_ID,DEPT_ID_OTHER')->where($uMap)->find();
                        $step['prcs_dept'] = $user['dept_id'] . ',' . $user['dept_id_other'];

                        // echo $step['prcs_dept'];
                        if ($step['prcs_dept']) {
                            $depts = explode(',', $step['prcs_dept']);
                        }
                        if ($sql !== '') {
                            $sql .= " and (DEPT_ID in (" . rtrim($step['prcs_dept'], ',') . ")";
                        } else {
                            $sql .= "(DEPT_ID in (" . rtrim($step['prcs_dept'], ',') . ")";
                        }

                        //获取副部门的条件
                        if ($depts) {
                            foreach ($depts as $key => $row) {
                                if ($row) {
                                    $sql .= " or DEPT_ID_OTHER like '%" . $row . "%'";
                                }
                            }
                        }
                        $sql .= ")";
                    } else if ($step['prcs_dept'] == 'ALL_DEPT') {
                        $dept_ids = M('department')->getField('dept_id', true);
                        $dept_ids = implode(',', $dept_ids);
                        if ($sql !== '') {
                            $sql .= ' and DEPT_ID in (' . $dept_ids . ')';
                        } else {
                            $sql .= 'DEPT_ID in (' . $dept_ids . ')';
                        }
                    }

                    if ($step['prcs_priv']) {
                        $privs = explode(',', $step['prcs_priv']);
                        //$map['USER_PRIV'] = array('in', $privs);     //角色条件
                        if ($step['prcs_priv']) {
                            if ($sql != '') {
                                $sql .= " and (USER_PRIV in (" . rtrim($step['prcs_priv'], ',') . ")";
                            } else {
                                $sql .= "(USER_PRIV in (" . rtrim($step['prcs_priv'], ',') . ")";
                            }
                        }

                        if ($privs) {
                            foreach ($privs as $key => $row) {
                                if ($row) {
                                    $sql .= " or USER_PRIV_OTHER like '%" . $row . "%'";
                                }
                            }
                        }
                        $sql .= ")";
                    }

                    $users = explode(',', $step['prcs_user']);
                    foreach ($users as $k => $u) {
                        if ($u) {
                            $users[$k] = '"' . $u . '"';
                        }
                    }
                    $users = implode(',', $users);
                    if ($step['prcs_user']) {
                        if ($sql != '') {
                            $sql .= " and USER_ID in (" . rtrim($users, ',') . ")";
                        } else {
                            $sql .= "USER_ID in (" . rtrim($users, ',') . ")";
                        }
                    }

                    //公文发送：最后一步显示发起人的姓名
                    if ($flow_id == 93 && $prcs_id == 8) {
                        $res_1 = M('flow_run')->field('BEGIN_USER')->where(" RUN_ID = $run_id and FLOW_ID = 93")->find();
                        $sql = " USER_ID = '" . $res_1['begin_user'] . "'";
                    }
                    //内部请示：最后一步显示发起人的姓名
                    if ($flow_id == 165 && $prcs_id == 6) {
                        $res_1 = M('flow_run')->field('BEGIN_USER')->where(" RUN_ID = $run_id and FLOW_ID = 165")->find();
                        $sql = " USER_ID = '" . $res_1['begin_user'] . "'";
                    }
                }else{
                    //非流程类选择人员
                    $sql = ' DEPT_ID != 0';
                }
            }

            $data = M('user')->field('USER_ID,USER_NAME,USER_PRIV,USER_PRIV_OTHER,DEPT_ID,DEPT_ID_OTHER')->where($sql)->limit($start, $limit)->select();
            //获取总条数
            $count = M('user')->where($sql)->count();

            foreach ($data as $k => $r) {
                $data[$k]['count'] = $count;
                if ($sql && $auto_type != 0) {
                    $data[$k]['checked'] = 1;
                }
            }
        }
        //$data[] = M('user')->field('USER_ID,USER_NAME,USER_PRIV,USER_PRIV_OTHER,DEPT_ID,DEPT_ID_OTHER')->where('user_id="zhangyingheng"')->find();
        return $data;
    }

    //下拉获取用户(所有用户，点击部门时暂时不能加载下拉插件)
    public function droploadUser() {
        $limit = $this->limit;
        $users = $this->getData('', '', '', '', I('dept_id'));


        $this->ajaxReturn($users);
    }

    //弹窗
    public function layer() {
        $type = I('type');
        $user_id = session('user_id');
        $dia_id = I('dia_id');
        $comment_id = I('comment_id');
        switch ($type) {
            case 1:
                //获取用户
                $departs = M('department')->order('DEPT_NO')->select();
                $this->departs = $departs;

                $this->flow_id = I('flow_id');
                $this->run_id = I('run_id');
                $this->prcs_id = I('prcs_id');
                $this->auto_type = I('auto_type');
                $this->id = I('id');    //流程外其他选择人员
                $this->table_key = I('key');  //工作计划模块用来区分不同选择人员的key

                $users = $this->getData(I('flow_id'), I('prcs_id'), I('run_id'), I('auto_type'), '', 8);

                //添加步驟名和是否会签标记到$data數組中
                $users = addPrcsname($users, I('flow_id'), I('prcs_id'));
                $count = $users[0]['count'];
                $this->pages = $this->pageLists($count);

                $this->users = $users;
                break;
            case 2:
                $flow_prcs = I('prcs_id');  //流程步骤
                $run_id = I('run_id');
                $flow_id = I('flow_id');
                $map['RUN_ID'] = $run_id;
                $map['FLOW_PRCS'] = $flow_prcs;
                //$prcs_id = M('flow_run_prcs')->where($map)->getField('prcs_id');

                unset($map['RUN_ID']);
                $map['FLOW_ID'] = $flow_id;
                $map['PRCS_ID'] = array('lt', $flow_prcs);
                $runs = M('flow_process')->field('FLOW_ID,PRCS_ID,PRCS_NAME')->where($map)->order('prcs_id')->select();
                foreach ($runs as $key => $row) {
                    $runs[$key]['run_id'] = $run_id;
                }
                //print_r($runs);
                $this->runs = $runs;
                $this->currFlowPrcs = I('prcs_id');
                $this->currPrcsId = I('currPrcs');
                break;
            case 3:
                //获取部门
                $this->depts = M('department')->order('DEPT_ID')->select();
                break;
            case 4:
                //获取回复日志的id
                $this->dia_id = $dia_id;
                $this->comment_id = $comment_id;
                break;
            case 5:
                $this->id = I('id');
                $this->is_end = I('is_end');
                break;
            case 6:
                //获取回复周报的id
                $this->id = I('id');
                $this->week_id = I('week_id');
                break;
            case 7:
                //获取角色
                $this->privs = M('user_priv')->order('PRIV_NO')->select();
                break;
            case 8:
                //获取公告
                $this->notify = M('notify')->where('NOTIFY_ID=' . I('id'))->find();
                break;
            case 9:
                //获取公告
                $this->notify = M('notify')->where('NOTIFY_ID=' . I('id'))->find();
                break;
            case 10:
                //取当月前12个月
                for ($i = 1; $i <= 12; $i++) {
                    if (count($arr) != 12) {
                        $month[date('Y-m', strtotime("-" . $i . " month"))] = date('Y年m', strtotime("-" . $i . " month")) . '月';
                    }
                }
                $this->months = $month;
                break;
        }

        $this->type = $type;
        $this->display('Base/layer');
    }

    //弹窗(日志查询选择人员)
    public function searchDiary() {
        $type = I('type');
        $user_id = session('user_id');

        switch ($type) {
            case 1:
                //获取用户
                $departs = M('department')->order('DEPT_NO')->select();
                $this->departs = $departs;

                $this->flow_id = I('flow_id');
                $this->run_id = I('run_id');
                $this->prcs_id = I('prcs_id');
                $this->auto_type = I('auto_type');
                $this->id = I('id');    //流程外其他选择人员
                $this->table_key = I('key');  //工作计划模块用来区分不同选择人员的key

                $users = $this->getData(I('flow_id'), I('prcs_id'), I('run_id'), I('auto_type'), '', 8);

                //添加步驟名和是否会签标记到$data數組中
                $users = addPrcsname($users, I('flow_id'), I('prcs_id'));
                $count = $users[0]['count'];
                $this->pages = $this->pageLists($count);

                $this->users = $users;
                break;
        }

        $this->type = $type;
        $this->display('Base/searchDiary');
    }

    //ajax分页显示用户姓名
    public function getAjaxPage() {
        $run_id = I('run_id');
        $prcs_id = I('prcs_id');
        $auto_type = I('auto_type');

        $dept_id = I('dept_id') ? I('dept_id') : '';
        if (strpos($dept_id, '.html')) {
            $end = strpos($dept_id, '.');
            $dept_id = substr($dept_id, 0, $end);
        }

        $flow_id = I('flow_id') ? I('flow_id') : 0;
        $p = I('get.p');
        $limit = 8;
        $list = $this->getData($flow_id, $prcs_id, $run_id, $auto_type, $dept_id, $limit);

        //添加步驟名和是否会签标记到$data數組中
        $list = addPrcsname($list, $flow_id, $prcs_id);
        foreach ($list as $key => $row) {
            $list[$key]['flow_id'] = $flow_id;
        }

        $page = new \Think\MyPage($list[0]['count'], $limit);
        $data['list'] = $list;
        $data['first'] = $page->first();
        $data['prev'] = $page->prev();
        $data['next'] = $page->next();
        $data['last'] = $page->last();
        $data['curr'] = $p;
        $data['page'] = explode(' ', $page->pageList_ajax());

        $this->ajaxReturn($data);
    }

    //按类型获取个人计划百分比
    //2018/3/14  计划模块中员工和公司领导需获取个人计划百分比, 统计模块中所有用户都要获取
    protected function userProcessDetail($planTypes) {
        //取周一和周日
        $week = getWeekDate();

        //本人
        foreach ($planTypes as $key => $row) {
            //取时间
//            switch ($row['type_name']) {
//                case '日计划':
////                            $map['_string'] = ' BEGIN_DATE between "' . $week[0] . '" and "' . $week[1] . '" and END_DATE between "' . $week[0] . '" and "' . $week[1] . '"';
//                    $map['_string'] = ' (BEGIN_DATE >= ' . $week[0] . ' or BEGIN_DATE <= ' . $week[1] . ') and END_DATE > ' . $week[1];
//                    break;
//                case '年度计划':
//                    $map['_string'] = ' END_DATE between "' . date('Y-01-01') . '" and "' . date('Y-12-31') . '" or END_DATE = "0000-00-00"';
//                    break;
//                default :
//                    $map['_string'] = ' END_DATE between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or END_DATE = "0000-00-00"';
//                    break;
//            }

            if (getPlanMode($row['type_id']) == 0) {
                $where['executor'] = array('like', '%' . session('user_id') . '%');
            } else {
                $where['MANAGER'] = session('user_id');
                $where['PARTICIPATOR'] = array('like', '%' . session('user_id') . '%');
            }

            $map['TYPE'] = $row['type_id'];
            $map['SMS_FLAG'] = 0;
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
            $plans[$row['type_id']] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
            $plans[$row['type_id']]['name'] = $row['type_name'];
        }
        foreach ($plans as $key => $row) {
            $total = $this->getPercent($row);
            $num = (count($row) - 1) ? count($row) - 1 : 0;
            if ($row[0]) {
                $count = (round(($total / ($num * 100)), 2) * 100) . '%';
            } else {
                $count = '0%';
            }
            $percent[$key]['name'] = $row['name'];
            $percent[$key]['count'] = $num;
            $percent[$key]['total'] = $count;
        }

        /*
          //取部门领导
          $pMap['PRIV_NO'] = array('between', [30, 40]);
          $privIds = M('user_priv')->where($pMap)->getField('user_priv', true);
          unset($map);
          if (in_array(session('user_priv'), $privIds)) {
          //部门领导
          unset($percent['user']);
          //取部门员工
          $dMap['DEPT_ID'] = session('dept_id');
          $deptUsers = M('user')->where($dMap)->getField('user_id', true);
          if (!is_array($deptUsers)) {
          $deptUsers[] = $deptUsers;
          }
          foreach ($planTypes as $p_key => $p_row) {
          //取时间
          switch ($p_row['type_name']) {
          case '周计划':
          //                            $map['_string'] = ' BEGIN_DATE between "' . $week[0] . '" and "' . $week[1] . '" and END_DATE between "' . $week[0] . '" and "' . $week[1] . '"';
          $map['_string'] = ' (BEGIN_DATE >= ' . $week[0] . ' or BEGIN_DATE <= ' . $week[1] . ') and END_DATE > ' . $week[1];
          break;
          case '年度计划':
          $map['_string'] = ' END_DATE between "' . date('Y-01-01') . '" and "' . date('Y-12-31') . '" or END_DATE = "0000-00-00"';
          break;
          default :
          $map['_string'] = ' END_DATE between "' . date('Y-m-01') . '" and "' . date('Y-m-31') . '" or END_DATE = "0000-00-00"';
          break;
          }
          foreach ($deptUsers as $u_key => $u_row) {
          $map['TYPE'] = $p_row['type_id'];
          //$map['SMS_FLAG'] = 0;
          $where['MANAGER'] = array('in', $u_row);
          $where['PARTICIPATOR'] = array('like', '%' . $u_row . '%');
          $where['_logic'] = 'or';
          $map['_complex'] = $where;
          $plans[$p_row['type_id']] = M('work_plan')->where($map)->order('BEGIN_DATE desc')->select();
          $plans[$p_row['type_id']]['name'] = $p_row['type_name'];
          }
          }
          }
         */
        return $percent;
    }

    protected function getPercent($data) {
        $finish = 0;
        foreach ($data as $key => $row) {
//            $map['PLAN_ID'] = $row['plan_id'];
//            $finish += M('work_detail')->where($map)->max('PERCENT');
            $finish += $row['total_percent'];   //只取每条的总进度
        }
        return $finish;
    }

}
